
const Promise = require('bluebird');
const yDb = require('../model/yunshijie');
const FastStatisticsDay = yDb.FastStatisticsDay;
const _ = require('lodash');
const moment = require('moment');

/**
 * 记录快讯的相关信息根据天数
 * @param par
 * @param type
 */
function recordFastStatisByDay(par, type) {
    let date = moment().format('YYYY-MM-DD');
    let ids = par.ids;
    //  如果不是数组的话， 换成数组
    if (!Array.isArray(ids)) {
        ids = [ids];
    }
    FastStatisticsDay.find({
        fid: ids,
        date: date
    }, null, {lean: true})
        .then((datas)=> {
            let i, updateArr = [], saveArr = [];
            let map = _.keyBy(datas, (item)=> item.fid);
            for (i = 0; i < ids.length; i++) {
                if (map[ids[i]]) {
                    updateArr.push(ids[i])
                } else {
                    let obj = {date: date, fid: ids[i]};
                    obj[`${type}`] = 1;
                    saveArr.push(obj);
                }
            }
            return Promise.props({
                //  存储
                save: new Promise((resolve, reject)=> {
                    FastStatisticsDay.create(saveArr, (err)=> {
                        if (err) {
                            return reject(err)
                        }
                        return resolve()
                    })
                }),
                //  修改
                update: FastStatisticsDay.updateMany({
                        fid: updateArr, date: date
                    },
                        FastStatisticsDay.operateByType(type))
                    .exec()
            })
        })
    //fixme 需要再写出执行结果没
}

module.exports = {
    //  修改或存储快讯每日统计
    recordFastStatisByDay: recordFastStatisByDay
};